package com.zeng.sys.filemd.servicemodule.transfer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zeng.nicecommon.util.ResponseUtil;
import com.zeng.sys.filemd.servicemodule.vo.FileRecordVo;
import com.zeng.sys.filemd.servicemodule.vo.FileServerVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Slf4j
public class FileHttpTransfer {

    CloseableHttpClient httpClient = HttpClientBuilder.create().build();

    private String address;

    private String uploadUri;

    private String downloadUri;

    private String deleteUri;

    private String dispatchDeleteUri;

    private ObjectMapper objectMapper = new ObjectMapper();

    public FileHttpTransfer(FileServerVo fileServerVo) {
        try {
            Map<String, Object> stringObjectMap = objectMapper.readValue(fileServerVo.getServerOption(), Map.class);

            address = (String) stringObjectMap.get("address");
            uploadUri = "http://" + address + "/server/upload";
            downloadUri = "http://" + address + "/server/download";
            deleteUri = "http://" + address + "/server/delete";
            dispatchDeleteUri = "http://" + address + "/server/batchDelete";
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        }
    }

    public byte[] download(String path) {
        try {

            HttpPost httpPost = new HttpPost(downloadUri);
            ContentType contentType = ContentType.create("text/plain", Charset.forName("utf-8"));
            HttpEntity httpEntity = MultipartEntityBuilder.create().addTextBody("path", path, contentType).build();
            httpPost.setEntity(httpEntity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);
            return bytes;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public ResponseUtil upload(FileRecordVo fileRecordVo) {
        fileRecordVo.setMultipartKey("file");
        HttpPost httpPost = new HttpPost(uploadUri);
        ContentType contentType = ContentType.create("text/plain", Charset.forName("utf-8"));
        byte[] dataWithByte = fileRecordVo.getDataWithByte();
        if (dataWithByte == null) {
            throw new RuntimeException("没有上传文件");
        }
        HttpEntity httpEntity = MultipartEntityBuilder.create()
                .addTextBody("multipartKey", fileRecordVo.getMultipartKey(), contentType)
                .addTextBody("path", fileRecordVo.getPath(), contentType)
                .addPart(fileRecordVo.getMultipartKey(), new ByteArrayBody(dataWithByte, fileRecordVo.getName()))
                .build();

        httpPost.setEntity(httpEntity);
        try {
            HttpResponse response = httpClient.execute(httpPost);
            return getResponseUtil(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public ResponseUtil delete(FileRecordVo fileRecordVo) {
        fileRecordVo.setMultipartKey("file");
        HttpPost httpPost = new HttpPost(deleteUri);
        ContentType contentType = ContentType.create("text/plain", Charset.forName("utf-8"));
        HttpEntity httpEntity = MultipartEntityBuilder.create()
                .addTextBody("path", fileRecordVo.getPath(), contentType)
                .build();
        httpPost.setEntity(httpEntity);
        try {
            HttpResponse response = httpClient.execute(httpPost);
            return getResponseUtil(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public ResponseUtil batchDelete(List<String> paths) {
        if (paths == null && paths.size() <= 0) {
            return null;
        }
        HttpPost httpPost = new HttpPost(dispatchDeleteUri);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");
        StringEntity httpEntity = null;
        try {
            httpEntity = new StringEntity(objectMapper.writeValueAsString(paths),"UTF-8");
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        httpPost.setEntity(httpEntity);
        try {
            HttpResponse response = httpClient.execute(httpPost);
            return getResponseUtil(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean  isSuccess(HttpResponse httpResponse) {
        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            return false;
        }
        return true;
    }

    public static ResponseUtil getResponseUtil(HttpEntity entity) {
        try {
            return new ObjectMapper().readValue(EntityUtils.toString(entity), ResponseUtil.class);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
